package com.yxy.utils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
 * 地区查询工具类
 */
@Slf4j
public class AreaUtil {
    // 请求头名
    private static final String HEADER_NAME = "User-Agent";
    // 请求头值
    private static final String HEADER_VALUE = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3";
    // Ip地址获取
    private static final String IP_URL = "https://api.suyanw.cn/api/ip.php";
    // 地区获取
    private static final String AREA_URL = "https://api.suyanw.cn/api/ipcha.php?ip=";

    /**
     * 获取ip
     * @return
     */
    public static String getIp(){
        log.info("获取ip地址");
        String ip = "";
        try{
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(IP_URL))
                    .header(HEADER_NAME, HEADER_VALUE)
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            ip = response.body();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println(ip);
        return ip;
    }

    /**
     * 获取地区（配合Gson）
     * @return
     */
    public static String getArea(String ip){
        log.info("获取地区");
        try{
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://api.suyanw.cn/api/ipcha.php?ip=" + ip))
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3")
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            Gson gson = new Gson();
            String jsonObject = gson.fromJson(response.body(), JsonObject.class).toString();
            String area = jsonObject.split(",")[1].split(":")[1].split(" ")[0];
            area = area.substring(1, area.length() - 1);
            return area;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

}
